package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * MybatisPlus字段填充审计
 *
 * @author siashan
 * @date 2023/5/11
 */
@Slf4j
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            this.strictInsertFill(metaObject, "createBy", String.class, loginUser.getUsername());
        } else {
            this.strictInsertFill(metaObject, "createBy", String.class, "SYSTEM");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        LoginUser loginUser = SecurityUtils.getLoginUser();


        if (loginUser != null) {
            this.strictInsertFill(metaObject, "updateBy", String.class, loginUser.getUsername());
        }
    }
}

